<template>
  <div>
    <el-row :gutter="20">
      <!-- 搜索表单 -->
      <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
        <el-form-item label="编 号" prop="taocanSn">
          <el-input v-model="queryParams.taocanSn" placeholder="请输入套餐编号" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="名 称" prop="taocanName">
          <el-input v-model="queryParams.taocanName" placeholder="请输入套餐名称" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据操作按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" icon="el-icon-edit" size="small" :disabled="single" @click="handleUpdate">修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-delete" size="small" :disabled="single" @click="handleDelete">删除
          </el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="taocanList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="taocanId" label="套餐Id" align="center" width="80" />
        <el-table-column prop="taocanSn" label="套餐编号" align="center" />
        <el-table-column prop="taocanName" label="套餐名称" align="center" />
        <!--el-table-column label="图片" align="center">
          <template slot-scope="scope">
            <div class="cell-item"><img class="img" :src="scope.row.url"></div>
          </template>
        </el-table-column-->
        <el-table-column prop="taocanPrice" label="套餐价格" align="center" />
        <el-table-column prop="taocanDescription" label="套餐描述" align="center" />
        <el-table-column prop="taocanStatus" label="套餐状态" align="center" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-edit" @click="handleDetail(scope.row)">详情</el-button>
            <el-button size="small" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="small" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页加载 -->
      <el-pagination :current-page="queryParams.pageNum" :page-sizes="[5, 10, 20, 50]" :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-row>

    <!-- 新增/修改对话框 默认不显示 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="套餐编号" prop="taocanSn">
          <el-input v-model="form.taocanSn" />
        </el-form-item>
        <el-form-item label="套餐名称" prop="taocanName">
          <el-input v-model="form.taocanName" />
        </el-form-item>
        <el-form-item label="套餐价格" prop="taocanPrice">
          <el-input v-model="form.taocanPrice" />
        </el-form-item>
        <el-form-item label="套餐描述" prop="taocanDescription">
          <el-input v-model="form.taocanDescription" />
        </el-form-item>
        <el-form-item label="套餐状态" prop="taocanStatus">
          <el-select v-model="form.taocanStatus" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="选项个数" v-if="title === '添加套餐'">
          <el-input-number v-model="num" size="mini" :min="1" label="选项数量"></el-input-number>
          <el-button type="primary" icon="el-icon-plus" size="medium" @click="showAddProductDialog">添加菜品</el-button>
        </el-form-item>
        <el-form-item label="套餐明细" v-if="title === '添加套餐'">
          <el-table v-loading="loading" :data="taocans" @selection-change="handleChange">
            <el-table-column prop="productDescription.url" label="图片" align="center">
              <template slot-scope="scope">
                <img :src="scope.row.productDescription.url" class="image" align="center">
              </template>
            </el-table-column>
            <el-table-column prop="productDescription.productName" label="菜名" align="center" width="100" />
            <el-table-column prop="productDescription.price" label="原价" align="center" />
            <el-table-column prop="quantity" label="数量" align="center" width="150">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.quantity" size="mini" :min="1" label="数量"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="addprice" label="加价" align="center" width="150">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.addprice" size="mini" :min="1" label="加价"></el-input-number>
              </template>
            </el-table-column>
            <!--el-table-column prop="highestOption" label="选项" align="center"/-->
            <el-table-column prop="taocanType" label="是否固定" align="center">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.taocanType" active-color="#13ce66" :active-value= "1" :inactive-value= "2">
                </el-switch>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="open = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="添加菜品" :visible.sync="addProductDialogVisible" :close-on-click-modal="false"
      @closed="resetAddProductDialog" class="dialog">
      <el-card class="box-card">
        <el-form ref="queryForm1" :model="queryParams1" :inline="true" label-width="68px">
          <el-form-item label="菜品名称" prop="productName">
            <el-input v-model="queryParams1.productName" placeholder="请输入菜品名称" clearable size="small"
              @keyup.enter.native="handleQueryProduct" />
          </el-form-item>
          <el-form-item label="菜品类别" prop="productId">
            <el-select v-model="queryParams1.categoryId" placeholder="请选择">
              <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName"
                :value="item.categoryId" @keyup.enter.native="handleQueryProduct" />
            </el-select>
          </el-form-item>
          <!-- 搜索按钮 -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryProduct">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery1">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="dataList" @selection-change="handleChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="productDescription.url" label="图片" width="100" align="center">
            <template slot-scope="scope">
              <img :src="scope.row.url" class="image" align="center">
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="菜名" align="center" width="100" />
          <el-table-column prop="productSn" label="编号" align="center" />
          <el-table-column prop="price" label="价格" align="center" />
        </el-table>

        <template>
          <!-- 分页加载 -->
          <el-pagination :current-page="queryParams1.pageNum" :page-sizes="[5, 10, 20, 50,100]"
            :page-size="queryParams1.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
            @size-change="handleSizeChange1" @current-change="handleCurrentChange1" />
        </template>
      </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addProductDialogVisible = false">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listAll
  } from '@/api/pos/category'
  import {
    listTaocanByPage,
    delTaocan,
    getTaocan,
    updateTaocan,
    addTaocan,
    listTaocanItem,
    list
  } from '@/api/pos/meal'
  import {
    listProductByPage
  } from '@/api/pos/product'
  import {
    getToken
  } from '@/utils/auth'
  export default {
    name: 'Meal',
    data() {
      return {
        activeName: '1',
        categoryOptions: [],
        // 下单界面的
        dataList: [],
        addProductDialogVisible: false,
        show: false,
        // 状态选项
        statusOptions: [{
            value: '在售',
            label: '在售'
          },
          {
            value: '下架',
            label: '下架'
          }
        ],
        // 表格数据
        taocanList: [],
        // 遮罩层
        loading: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 5,
          taocanId: null,
          taocanName: null
        },
        // 查询参数（添加菜品的，后面有“1”的都是添加菜品里面的）
        queryParams1: {
          pageNum: 1,
          pageSize: 5,
          productSn: null,
          productName: null,
          categoryId: null
        },
        form: {
          taocanName: null,
          taocanId: null
        },
        form1: {
          productName: null,
          taocanId: null
        },
        rules: {
          taocanName: [{
            required: true,
            message: '请输入套餐名称',
            trigger: 'blur'
          }],
          taocanId: [{
            required: true,
            message: '请选择类别ID',
            trigger: 'change'
          }]
        },
        num: 1,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 总页数
        total: 0,
        // 上传图片数据
        dialogImageUrl: '',
        disabled: false,
        fileList: [],
        uploadApi: process.env.VUE_APP_BASE_API + '/oss/upload',
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        taocans: []
      }
    },
    created() {
      this.getList()
      this.getList1()
      this.getCategoryOptions()
    },
    methods: {
      /** 查询下拉列表选型 */
      getCategoryOptions() {
        // 访问后端接口，查外键所有对象
        // 结果赋值this.categoryOptions
        listAll().then(response => {
          this.categoryOptions = response.data
        })
      },
      /** 处理分页 */
      handleSizeChange1(val) {
        this.queryParams1.pageSize = val
        this.getList()
      },
      handleCurrentChange1(val) {
        this.queryParams1.pageNum = val
        this.getList()
      },
      handleClick() {
        this.queryParams.pageNum = 1
        if (this.activeName === '21') {
          this.getTaocan()
        } else {
          this.queryParams1.categoryId = parseInt(this.activeName)
          this.getList1()
        }
      },
      getList() {
        this.loading = true
        listTaocanByPage(this.queryParams).then(response => {
          this.taocanList = response.data.list
          this.total = response.data.total
          this.loading = false
        })
      },
      getList1() {
        this.loading = true
        // 结果赋值this.dataList
        listProductByPage(this.queryParams1).then(response => {
          this.dataList = response.data.list
          this.total = response.data.total
          this.loading = false
        })
      },
      handleQueryProduct() {
        this.queryParams.pageNum = 1
        this.getList1()
      },
      showAddProductDialog() {
        this.addProductDialogVisible = true
      },
      resetAddProductDialog() {
        this.selectedProduct = ''
        this.dishCount = 1
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },


      /** 重置按钮操作 */
      resetQuery() {
        this.$refs.queryForm.resetFields()
        this.getList()
      },
      resetQuery1() {
        this.$refs.queryForm1.resetFields()
        this.getList1()
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => {})
      },

      /** 表单重置 */
      resetForm() {
        // 可进行数据初始化工作
        this.form = {
          taocanName: null,
          taocanId: null
        }
        this.fileList = []
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.taocanId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },

      /** 详情 **/
      handleDetail(row) {
        this.show = true
        const taocanSn = row.taocanSn
        listTaocanItem(taocanSn).then(response => {
          const productName = response.data.map(item => item.productName)
          console.log(productName)
          this.$notify({
            title: '套餐详情',
            dangerouslyUseHTMLString: true,
            message: '🦄套餐内容为： ' + productName
          })
        })
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.resetForm()
        this.open = true
        this.title = '添加套餐'
        this.taocans = []
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.resetForm()
        const taocanSn = row.taocanSn || this.ids
        list(taocanSn).then(response => {
          const data = response.data[0]
          this.form = data
          //   taocanSn: data.map(item => item.taocanSn),
          //   taocanName: data.map(item => item.taocanName),
          //   taocanId: data.map(item => item.taocanId),
          //   taocanPrice: data.map(item => item.taocanPrice),
          //   taocanStatus: data.map(item => item.taocanStatus),
          //   taocanDescription: data.map(item => item.taocanDescription)
          // }
          // const index = data.findIndex((item)=> item.)
          console.log(data)
          this.open = true
          this.title = '修改套餐'
          // this.fileList.push(data[0])
          // console.log(this.fileList)
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const taocanId = row.taocanId || this.ids
        this.$confirm('是否确认删除ID为"' + taocanId + '"的数据项?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(function () {
            return delTaocan(taocanId)
          })
          .then(() => {
            this.getList() // 刷新数据
            this.$message.success('删除成功')
          })
          .catch(() => {})
      },

      /** 提交按钮 */
      submitForm: function () {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.taocanId != null) {
              updateTaocan(this.form).then(response => {
                this.$message.success(response.msg)
                this.getList()
                this.cancel()
              })
            } else {
              this.form.taocanes = this.taocans
              addTaocan(this.form).then(response => {
                this.$message.success(response.msg)
                this.getList()
                this.cancel()
              })
            }
          }
        })
      },
      /** 取消按钮 */
      cancel() {
        this.open = false
        this.title = ''
        this.resetForm()
      },
      /** 处理分页 */
      handleSizeChange(val) {
        this.queryParams.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.queryParams.pageNum = val
        this.getList()
      },
      /** 上传成功时 **/
      onUploadSuccess(response, file, fileList) {
        // 处理上传成功返回的结果
        console.log(response)
        this.form.ossId = response.data.ossId
      },
      //多选菜品
      handleChange(val) {
        const data = val
        console.log(data)
        this.taocans = []
        data.forEach(item => {
          const taocanItem = {}
          taocanItem.productDescription = item
          taocanItem.addprice = 0
          taocanItem.highestOption = this.num
          taocanItem.delFlag = '0'
          taocanItem.productId = item.productId
          taocanItem.quantity = 1
          taocanItem.taocanType = 1
          this.taocans.push(taocanItem)
        })

      },
    }
  }
</script>

<style scoped>
  .box-card {
    height: 100%;
  }

  .menuCard {
    margin: 3px
  }

  .price {
    color: blue;
    font-size: 13px
  }

  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .image {
    width: 100%;
    height: 80px;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }

  .dialog {
    height: 100%;
    overflow-y: auto
  }
</style>
